#include "operatorResponse.h"
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>

OperatorResponse::OperatorResponse() : success(false) {
	doc.SetObject();
}

OperatorResponse::OperatorResponse(const bool& success) : success(success)
{
	doc.SetObject();
}

OperatorResponse::OperatorResponse(const bool& success, const String& message) : success(success), message(message)
{
	doc.SetObject();
}

JsonDoc& OperatorResponse::jsonDoc()
{
	return doc;
}

JsonDoc& OperatorResponse::jsonSerialize()
{
	JsonDoc::AllocatorType& allocator = doc.GetAllocator();
	doc.AddMember(L"success", success, allocator);
	if (!message.empty()) {
		JsonValue v(rapidjson::kStringType);
		v.SetString(message.c_str(), message.length(), allocator);
		doc.AddMember(L"message", v, allocator);
	}
	return doc;
}

JsonDoc& OperatorResponse::jsonDeserialize(const String& json)
{
	if (json.empty()) {
		return doc;
	}
	doc.Parse(json.c_str());
	JsonValue::ConstMemberIterator it = doc.FindMember(L"success");
	if (it != doc.MemberEnd() && it->value.IsBool()) {
		success = it->value.GetBool();
	}
	it = doc.FindMember(L"message");
	if (it != doc.MemberEnd() && it->value.IsString()) {
		message = it->value.GetString();
	}
	return doc;
}

String OperatorResponse::jsonStr()
{
	JsonStringBuffer stringBuffer;
	rapidjson::Writer<JsonStringBuffer,rapidjson::UTF16<>,rapidjson::UTF16<>> writer(stringBuffer);
	doc.Accept(writer);
	return stringBuffer.GetString();
}

bool OperatorResponse::isSuccess() const
{
	return success;
}

const String& OperatorResponse::getMessage() const
{
	return message;
}
